<template>
  <div class="app-container home">
    <div class="bg_fff p_10 listbody">
      <div class="flexrowbetween flexwrapper mb_15" style="align-items: flex-start">
        <div class="flex">
          <div
            class="iconbox flexcenter commhover mr_10"
            @click="resetQuery"
          >
            <i class="el-icon-refresh f-20" :class="{ rotate: isrefresh }"></i>
          </div>
          <el-button plain type="primary" size="mini" @click="handleAdd">添加</el-button>
          <!-- <el-button plain type="danger" :disabled="multiple" size="mini" @click="handleDelete(1)">删除</el-button> -->
        </div>
        <div>
          <!-- <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            label-width="0"
          >
            <el-form-item>
              <el-dropdown trigger="click" @command="handleCommand">
                <el-button size="mini" class="nol_border plr_9">
                  <svg-icon class-name="f-14" icon-class="export" />
                  <i class="el-icon-caret-bottom el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-for="(item, index) in exportlist"
                    :key="index"
                    :command="item.id"
                    >{{ item.name }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </el-form-item>
          </el-form> -->
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        ref="tablelayout"
        class="commtable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column align="center"
          label="ID"
          prop="id"
          width="120"
        ></el-table-column>
        <el-table-column align="center"
          label="名称"
          prop="name"
        ></el-table-column>
        <el-table-column label="状态"
          align="center"
        >
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                inactive-color="#ccc"
                :active-value="1"
                :inactive-value="0"
                @change="changeStatus(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
            prop="created_at"
            label="操作"
            width="160"
            fixed="right"
            align="center"
        >
          <template slot-scope="scope">
            <div class="flex btnflex">
                <div class="commhover btn_green c_fff mr_10"
                    @click="handleUpdate(scope.row)">
                    <i class="el-icon-edit f-14"></i> 编辑
                </div>
                <div class="commhover btn_yellow c_fff"
                    @click="handleDelete(scope.row)">
                    <i class="el-icon-delete f-14"></i> 删除
                </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.num"
        @pagination="getList"
      />
    </div>
    <el-dialog :title="title"
      :visible.sync="open"
      width="680px"
      class="dialogheaderbg"
      :before-close="handleCloseAdd"
      :close-on-click-modal='false'>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <!-- <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox> -->
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <!-- <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox> -->
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <!-- <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="handleCloseAdd">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { getRoleList,getMenuList,roleAdd,getRoleInfo,roleEdit,roleDelete,roleStatusOpen, roleStatusClose} from '@/api/roles'
import { handleTree } from '@/utils/index';
export default {
  data() {
    return {
      queryParams: {
        page: 1,
        num: 10,
      },
      total: 1,
      loading: false,
      tableData: [],
      checkedOption: [],
      isrefresh: false,
      selectoptions: [
        { id: 1, label: "ID" },
        { id: 2, label: "状态" },
        { id: 3, label: "订单号" },
        { id: 4, label: "会员" },
        { id: 5, label: "昵称" },
        { id: 6, label: "金额" },
        { id: 7, label: "到账金额" },
        { id: 8, label: "支付平台" },
        { id: 9, label: "支付单号" },
        { id: 10, label: "支付时间" },
        { id: 11, label: "备注" },
        { id: 12, label: "添加时间" },
      ],
      dialogAddVisible: false,
      multiple: true,
      isadd: true,
      title: "",
      // 是否显示弹出层
      open: false,
      row: null,
      menuNodeAll: false,
      form: {},
      // 菜单列表
      menuOptions: [],
      originOptions:[],//原始数据
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择状态", trigger: "change" }
        ],
        // roleSort: [
        //   { required: true, message: "角色顺序不能为空", trigger: "blur" }
        // ]
      }
    };
  },

  props: {
    type: {
      type: Number,
      default: 1,
    },
  },

  created() {
    this.getList()
    this.getMenuTreeselect()
  },

  methods: {
    getList() {
      this.loading = true;
      getRoleList(this.queryParams).then((response) => {
        this.tableData = response.data.list;
        this.total = response.data.count;
        this.loading = false;
      });
      this.isrefresh = false;
      this.loading = false;
    },

    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },

    resetQuery() {
      this.isrefresh = true;
      this.resetForm("queryForm");
      this.handleQuery();
    },

    handleSelectionChange(selection) {
      this.rowids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },

    reset(){
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuNodeAll = false
      this.form = {
        id: undefined,
        name: undefined,
        status: 1,
        menuId:[]
      };
      this.resetForm("form");
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getMenuTreeselect();
      this.open = true;
      this.title = "添加角色";
    },

    handleCloseAdd(){
        this.open = false
    },

    /** 查询菜单树结构 */
    getMenuTreeselect() {
      getMenuList().then(response => {
        this.menuOptions = handleTree(response.data);
        this.originOptions = response.data.map(item=>({...item, allname:item.app+item.controller+item.action}))
      });
    },

    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },

    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
      }
    },

    handleCommand(command) {
      console.log(command);
    },

    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(roleId) {
      return roleMenuTreeselect(roleId).then(response => {
        this.menuOptions = response.menus;
        return response;
      });
    },

    changeStatus(item){
      let _this = this
      if(item.status == 1){
        this.$modal.confirm('是否确认开启角色名称"' + item.name + '"的数据项？').then(function() {
          roleStatusOpen({role_id:item.id}).then(res=>{
            _this.$message.success("开启成功");
            _this.getList()
          }).catch(()=>{
            item.status = item.status = 0
          })
        }).catch(()=>{
          item.status = item.status = 0
        })
      }else{
        this.$modal.confirm('是否确认关闭角色名称"' + item.name + '"的数据项？').then(function() {
          roleStatusClose({role_id:item.id}).then(res=>{
            _this.$message.success("关闭成功");
            _this.getList()
          })
        }).catch(()=>{
          item.status = item.status = 1
        })
      }
      
    },

    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset()
      // await 
      // const roleId = row.roleId || this.ids
      // const roleMenu = this.getRoleMenuTreeselect(roleId);
      getRoleInfo({id:row.id}).then(res => {
        let data = res.data.role
        let checked = res.data.checked.map(item=>item.replaceAll('/',''))
        console.log('checked:',checked, this.originOptions)
        this.form.id = data.id;
        this.form.name = data.name
        this.form.status = data.status
        this.open = true;
        this.$nextTick(() => {
          checked.forEach(check=>{
            this.originOptions.forEach(item => {
              if(check == item.allname){
                console.log('-----check----')
                this.$nextTick(()=>{
                  this.$refs.menu.setChecked(item.id, true ,false);
                })
              }
            })
          })
          // roleMenu.then(res => {
          //   let checkedKeys = res.checkedKeys
          //   checkedKeys.forEach((v) => {
          //       this.$nextTick(()=>{
          //           this.$refs.menu.setChecked(v, true ,false);
          //       })
          //   })
          // });
        });
        this.title = "修改角色";
      });
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            this.form.menuId = this.getMenuAllCheckedKeys();
            roleEdit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.menuId = this.getMenuAllCheckedKeys();
            roleAdd(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      let infoIds = row.id 
      // if(row == 1){
      //   infoIds = this.rowids
      // }
      this.$modal.confirm('是否确认删除访问编号为"' + infoIds + '"的数据项？').then(function() {
        return roleDelete({id:infoIds});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.iconbox {
  width: 32px;
  height: 32px;
  border: 1px solid #eee;
  border-radius: 2px;
}
</style>
